package com.hui.mail;

import com.hui.server.entity.Employee;
import com.hui.server.entity.MailConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.mail
 * @Author: HUI
 * @CreateTime: 2022-04-15 22:20
 * @Description: 邮件发送
 */

@Component
@Slf4j
@RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
public class MailConsumer {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 邮件发送
     */
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message<Employee> message, Channel channel) {
        Employee employee = message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //拿到 correlation 的msgId
        String msgId = (String) headers.get("spring_returned_message_correlation");
        log.info("取到msgID：{}", msgId);

        //拿到tag
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        log.info("取到tag：{}", tag);

        //hash redis对象
        HashOperations hash = redisTemplate.opsForHash();

        try {
            if (hash.hasKey(MailConstants.REDIS_HASH_KEY, msgId)) {
                log.info("消息已经被消费：{}", msgId);
                /**
                 * 手动确认消息
                 * tag:消息序号
                 * multiple:是否多条
                 */
                channel.basicAck(tag, false);
                return;
            }

            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(employee.getEmail());
            helper.setSubject("入职邮件");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            //发送邮件
            javaMailSender.send(msg);
            log.info("邮件发送成功！");
            //消息存入redis
            hash.put(MailConstants.REDIS_HASH_KEY, msgId, "ok");
            //手动确认消息
            channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
                /*
                    否定确认，表示接收失败
                    1、tag：消息序号
                    2、multiple：是否确认多条
                    3、requeue：是否返回到队列
                 */
                channel.basicNack(tag,false,true);
            } catch (IOException ioException) {
                log.error("消息确认失败=====>{}", ioException.getMessage());
//                ioException.printStackTrace();
            }
            log.error("MailReceiver + 邮件发送失败========{}", e.getMessage());
//            e.printStackTrace();
        }
    }


    /**
     * 未开启应答，导致重复接收消息
     * @param employee
     */
/*    @RabbitHandler
    public void receiveMsg(Employee employee) {
        MimeMessage message = javaMailSender.createMimeMessage();
        log.info("要发送的邮件：{}",employee);
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(employee.getEmail());
            helper.setSubject("入职邮件");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(message);

            log.info("发送成功！");
        } catch (MessagingException ignored) {
            log.error("发送失败！");
        }
    }
 */
}
